package com.xuelang.pipeline.worker.entry.crd.tekton;

import com.alibaba.fastjson.JSON;
import com.xuelang.pipeline.worker.app.crd.tekton.TektonPipelineService;
import com.xuelang.pipeline.worker.client.common.result.ApiResult;
import com.xuelang.pipeline.worker.client.crd.IPipelineService;
import com.xuelang.pipeline.worker.client.crd.dto.PipelineDTO;
import com.xuelang.pipeline.worker.client.crd.dto.PipelineRunDTO;
import com.xuelang.pipeline.worker.client.crd.tekton.v1beta.V1PipelineList;
import com.xuelang.pipeline.worker.client.crd.tekton.v1beta.V1PipelineRunList;
import com.xuelang.pipeline.worker.client.crd.tekton.v1beta.pipeline.V1Beta1Pipeline;
import com.xuelang.pipeline.worker.client.crd.tekton.v1beta.pipeline.V1Beta1PipelineRun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;
import java.util.List;

/**
 * @author liuyuan.ly
 * @since 2024/5/30 15:15
 */
@RestController
@RequestMapping("/pipeline/worker/")
public class TektonController implements IPipelineService {

    @Autowired
    private TektonPipelineService tektonPipelineService;

    @Override
    public ApiResult<Boolean> createPipeline(PipelineDTO dto) {
        V1Beta1Pipeline tektonPipeline = tektonPipelineService.saveOrUpdateTektonPipeline(dto);
        return ApiResult.success(true);
    }

    @Override
    public ApiResult<List<V1Beta1Pipeline>> getPipelineList(PipelineDTO dto) {
        V1PipelineList pipelineList = tektonPipelineService.getTektonPipeline(dto);
        return ApiResult.success(pipelineList.getItems());
    }

    @Override
    public ApiResult<Boolean> createPipelineRun(PipelineRunDTO dto) {
        V1Beta1PipelineRun tektonPipelineRun = tektonPipelineService.createTektonPipelineRun(dto);
        return ApiResult.success(true);
    }

    @Override
    public ApiResult<String> getPipelineRunList(PipelineRunDTO dto) {
        V1PipelineRunList pipelineRunList = tektonPipelineService.getTektonPipelineRun(dto);
        return ApiResult.success(JSON.toJSONString(pipelineRunList.getItems()));
//        return ApiResult.success(pipelineRunList.getItems());
    }

    @Override
    public ApiResult<Boolean> cancelPipelineRun(@Valid PipelineRunDTO pipelineRunDTO) {
        return ApiResult.success(tektonPipelineService.cancelPipelineRun(pipelineRunDTO));
    }

}
